package cn.com.lib.utils;

import android.content.Context;
import android.util.DisplayMetrics;

/** @author maizi
 * ValueUtils.java
 * 2015年5月21日
 * 与界面显示有关的工具类
 * 1、px、dp、sp相互转换
 * 
 * 
 */
public class DisplayUtils {
	 /** {@link #TYPE_DIMENSION} complex unit: Value is raw pixels. */
    public static final int COMPLEX_UNIT_PX = 0;
    /** {@link #TYPE_DIMENSION} complex unit: Value is Device Independent
     *  Pixels. */
    public static final int COMPLEX_UNIT_DIP = 1;
    /** {@link #TYPE_DIMENSION} complex unit: Value is a scaled pixel. */
    public static final int COMPLEX_UNIT_SP = 2;
    /** {@link #TYPE_DIMENSION} complex unit: Value is in points. */
    public static final int COMPLEX_UNIT_PT = 3;
    /** {@link #TYPE_DIMENSION} complex unit: Value is in inches. */
    public static final int COMPLEX_UNIT_IN = 4;
    /** {@link #TYPE_DIMENSION} complex unit: Value is in millimeters. */
    public static final int COMPLEX_UNIT_MM = 5;
    
	
	/** 将某种格式转化为px
	/** @param unit 被转换的格式
	/** @param value 被转换的值
	/** @return
	 */
	public static float transDimensionPx(Context context,int unit,float value){
		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		switch (unit) {
        case COMPLEX_UNIT_PX:
            return value;
        case COMPLEX_UNIT_DIP:
            return value * metrics.density;
        case COMPLEX_UNIT_SP:
            return value * metrics.scaledDensity;
        case COMPLEX_UNIT_PT:
            return value * metrics.xdpi * (1.0f/72);
        case COMPLEX_UNIT_IN:
            return value * metrics.xdpi;
        case COMPLEX_UNIT_MM:
            return value * metrics.xdpi * (1.0f/25.4f);
        }
        return 0;
	}
	
	/**
     * 将px值转换为sp值，保证文字大小不变
     * @param pxValue
     * @param fontScale（DisplayMetrics类中属性scaledDensity）
     */ 
    public static float px2sp(Context context, float pxValue) { 
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 
        return pxValue / fontScale + 0.5f; 
    } 
    /**
     * 将sp值转换为px值，保证文字大小不变
     * @param spValue
     * @param fontScale（DisplayMetrics类中属性scaledDensity）
     */ 
    public static float sp2px(Context context, float spValue) { 
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; 
        return spValue * fontScale + 0.5f; 
    } 
	/**dip转px
	 * @param dipValue
	 */
	public static int dip2px(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}
	/** px转dip
	 * @param pxValue
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

}
